<template>
  <el-dialog
    :title="formData.id?'编辑页面':'添加页面'"
    :visible="showDialog"
    width="45%"
    @close="closeFn"
  >
    <el-form ref="form" label-width="50px" :rules="rules" :model="formData">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <quill-editor v-model="formData.content" @blur="$refs.form.validateField('content')" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { addPage, pagesId, redact } from '@/api/page'
export default {
  components: {
    quillEditor
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        content: ''
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    closeFn() {
      // 关闭弹窗
      this.$emit('update:showDialog', false)
      // 清除数据
      this.formData = {
        title: '',
        content: ''
      }
      //   清空校验
      this.$refs.form.resetFields()
    },
    async submit() {
      // 校验
      await this.$refs.form.validate()
      if (this.formData.id) {
        // 编辑
        await redact(this.formData)
        // 提示用户
        this.$message.success('成功编辑')
      } else {
        // 添加数据
        await addPage(this.formData)
        // 提示用户
        this.$message.success('成功添加')
      }
      // 关闭弹窗
      this.closeFn()
      // 页面刷新
      this.$emit('updateEvent')
    },
    // 编辑功能
    async pagesId(id) {
      const res = await pagesId(id)
      this.formData = res
    }
  }
}
</script>

<style>

</style>
